﻿using UnityEngine;
using UnityEngine.UI;

namespace CGF
{
    [ExecuteInEditMode]
    public class TextScale : MonoBehaviour
    {
        public int length1 = 5;
        public float scale1 = 1;
        public int length2 = 10;
        public float scale2 = 0.5f;
        public float minScale = 1;
        public float maxScale = 1;

        Text text;
        Line line;
        int length;

        void Start()
        {
            if (!text) text = GetComponent<Text>();
            text.RegisterDirtyVerticesCallback(OnContentChange);
            OnContentChange();
        }

        void OnContentChange()
        {
            line = new Line(length1, scale1, length2, scale2);
            float scale = 1;
            if (text.text.Length > length1)
            {
                scale = line.k * text.text.Length + line.b;
            }
            if (scale < minScale) scale = minScale;
            if (scale > maxScale) scale = maxScale;
            transform.localScale = Vector3.one * scale;
        }

#if UNITY_EDITOR
        public void Update()
        {
            if (!Application.isPlaying)
            {
                if (!text) text = GetComponent<Text>();
                if (length != text.text.Length)
                {
                    OnContentChange();
                    length = text.text.Length;
                }
            }
        }
#endif
    }
}
